<template>
  <view class="container">
    <!-- 商品图片轮播 -->
    <swiper class="swiper" :indicator-dots="true" :autoplay="true" circular>
      <swiper-item v-for="(img, index) in goodsInfo.images" :key="index">
        <image :src="img" mode="aspectFill" class="slide-image" />
      </swiper-item>
    </swiper>

    <!-- 价格区域 -->
    <view class="price-section">
      <view class="price-row">
        <text class="current-price">{{ priceDisplay }}</text>
        <text class="original-price" v-if="linePriceDisplay"
          >{{ linePriceDisplay }}</text
        >
        <text class="sales">已售{{ goodsInfo.soldQuantity || 0 }}</text>
      </view>

      <view class="tags-row">
        <text class="discount-tag" v-for="index in 4" :key="index">满减</text>
        <view class="coupon-link">
          领券 <text class="icon-arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 标题区域 -->
    <view class="title-section">
      <text class="product-title">{{ goodsInfo.name }}</text>
      <button class="share-btn" @tap="share">
        <text>分享</text>
      </button>
    </view>

    <!-- 规格选择 -->
    <view 
      class="selection-section" 
      @tap="goodsInfo.openSpec === 1 ? openSpecPopup() : null"
    >
      <view class="selection-row">
        <text class="label">已选</text>
        <text class="value">{{ 
          goodsInfo.openSpec === 1 
            ? (selectedSpecText || "请选择规格") 
            : "单规格" 
        }}</text>
        <text class="icon-arrow" v-if="goodsInfo.openSpec === 1">›</text>
      </view>
    </view>

    <!-- 评价区域 -->
    <view class="rating-section">
      <view class="rating-header">
        <text class="rating-title">商品评价(47)</text>
        <view class="rating-more">
          <text class="rating-score">95.7% 好评</text>
          <text class="icon-arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <block v-if="Array.isArray(goodsInfo.detail)">
        <image
          v-for="(img, index) in goodsInfo.detail"
          :key="index"
          :src="img"
          mode="widthFix"
          class="detail-image"
        />
      </block>
      <rich-text v-else :nodes="goodsInfo.detail"></rich-text>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-buttons">
        <view class="icon-btn" @tap="navTo('/pages/index/index')">
          <uni-icons type="home" size="24" color="#666" />
          <text>首页</text>
        </view>
        <view class="icon-btn" @tap="toggleCollect">
          <uni-icons
            :type="isCollected ? 'star-filled' : 'star'"
            size="24"
            :color="isCollected ? '#ff4444' : '#666'"
          />
          <text>收藏</text>
        </view>
        <view class="icon-btn" @tap="navTo('/pages/cart/cart')">
          <uni-icons type="cart" size="24" color="#666" />
          <text>购物车</text>
        </view>
      </view>
      <view class="main-buttons">
        <button class="add-cart-btn" @tap="handleAddToCart">加入购物车</button>
        <button class="buy-btn" @tap="handleBuyNow">立即购买</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <spec-popup
      ref="specPopup"
      :goods-info="goodsInfo"
      @confirm="handleSpecConfirm"
    />
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { goodsService } from "@/services/goods";
import { cartService } from "@/services/cart";
import { useUserStore } from "@/store/userStore"; // 引入用户 store
import { useCartStore } from "@/store/cartStore"; // 引入购物车 store
import SpecPopup from "./components/spec-popup.vue";

// 初始化 store
const userStore = useUserStore();
const cartStore = useCartStore();

// 响应式数据声明
const goodsInfo = ref({}); // 商品信息
const isCollected = ref(false); // 是否已收藏
const selectedSpecs = ref([]); // 已选规格数组
const quantity = ref(1); // 商品数量
const selectedSku = ref(null); // 已选中的SKU
const specPopup = ref(null); // 规格弹窗引用
const buyType = ref("cart"); // 购买类型：cart-加入购物车，buy-立即购买

// 计算属性
// 已选规格文本展示
const selectedSpecText = computed(() => {
  if (!selectedSpecs.value.length) return "";
  return goodsInfo.value.specs
    ?.map((group, index) => {
      return group.values[selectedSpecs.value[index]];
    })
    .join("，");
});

// 添加价格显示相关的计算属性
const priceDisplay = computed(() => {
  // 如果已选择SKU，显示对应SKU的价格
  if (selectedSku.value) {
    return `¥${selectedSku.value.salePrice}`;
  }
  
  // 如果是多规格商品且未选择规格，显示价格区间
  if (goodsInfo.value.openSpec === 1 && goodsInfo.value.skus?.length > 0) {
    const prices = goodsInfo.value.skus.map(sku => sku.salePrice);
    const minPrice = Math.min(...prices);
    const maxPrice = Math.max(...prices);
    return minPrice === maxPrice ? `¥${minPrice}` : `¥${minPrice}~¥${maxPrice}`;
  }
  
  // 默认显示商品价格
  return `¥${goodsInfo.value.salePrice || 0}`;
});

// 划线价显示
const linePriceDisplay = computed(() => {
  // 如果已选择SKU，显示对应SKU的划线价
  if (selectedSku.value && selectedSku.value.linePrice) {
    return `¥${selectedSku.value.linePrice}`;
  }
  
  // 如果是多规格商品且未选择规格，显示划线价区间
  if (goodsInfo.value.openSpec === 1 && goodsInfo.value.skus?.length > 0) {
    const prices = goodsInfo.value.skus
      .filter(sku => sku.linePrice)
      .map(sku => sku.linePrice);
    
    if (prices.length > 0) {
      const minPrice = Math.min(...prices);
      const maxPrice = Math.max(...prices);
      return minPrice === maxPrice ? `¥${minPrice}` : `¥${minPrice}~¥${maxPrice}`;
    }
  }
  
  // 默认显示商品划线价
  return goodsInfo.value.originalPrice ? `¥${goodsInfo.value.originalPrice}` : '';
});

// 获取商品详情数据
const getGoodsDetail = async (spuId) => {
  try {
    const res = await goodsService.getGoodsDetail(spuId);
    console.log("商品原始数据:", res.data);
    if (res.success) {
      // 处理商品数据
      const data = res.data;
      
      // 处理图片数组
      const images = [data.primaryImage];
      if (data.images) {
        try {
          const additionalImages = JSON.parse(data.images);
          images.push(...additionalImages);
        } catch (e) {
          console.error("解析图片数组失败:", e);
        }
      }

      // 构建商品信息对象
      goodsInfo.value = {
        id: data.spuId,
        name: data.title,
        salePrice: data.salePrice,
        originalPrice: data.linePrice,
        description: data.brief,
        images: images,
        detail: data.desc ? JSON.parse(data.desc) : [],
        openSpec: data.openSpec,
        soldQuantity: data.soldQuantity,
        // 处理规格数据
        specs: data.specs?.map(spec => ({
          name: spec.specName,
          specId: spec.specId,
          values: data.specValues
            .filter(value => value.specId === spec.specId)
            .map(value => ({
              valueId: value.valueId,
              valueName: value.valueName
            }))
        })) || [],
        // 处理SKU数据
        skus: data.skus?.map(sku => ({
          skuId: sku.skuId,
          salePrice: sku.salePrice,
          stock: sku.stock,
          specValues: sku.specValues,
          linePrice: sku.linePrice,
          code: sku.code
        })) || []
      };

      // 处理无规格商品的默认SKU
      if (!data.specs || data.specs.length === 0) {
        selectedSku.value = {
          id: data.spuId,
          salePrice: data.salePrice,
          stock: data.spuStockQuantity || 99
        };
      }

      // 初始化规格选择数组
      selectedSpecs.value = new Array(goodsInfo.value.specs?.length || 0).fill(-1);
    }
  } catch (error) {
    console.error("获取商品详情失败:", error);
    uni.showToast({
      title: "获取商品信息失败",
      icon: "none"
    });
  }
};

// 检查商品收藏状态
const checkCollect = async (spuId) => {
  try {
    if (!goodsService.checkCollect) {
      console.warn("收藏接口未实现");
      return;
    }

    const res = await goodsService.checkCollect(spuId);
    if (res.success) {
      isCollected.value = res.data;
    }
  } catch (error) {
    console.error("检查收藏状态失败:", error);
  }
};

// 切换商品收藏状态
const toggleCollect = async () => {
  try {
    if (!goodsService.toggleCollect) {
      uni.showToast({
        title: "收藏功能暂开放",
        icon: "none",
      });
      return;
    }

    const res = await goodsService.toggleCollect(goodsInfo.value.id);
    if (res.success) {
      isCollected.value = !isCollected.value;
      uni.showToast({
        title: isCollected.value ? "收藏成功" : "已取消收藏",
        icon: "success",
      });
    }
  } catch (error) {
    console.error("操作收藏失败:", error);
    uni.showToast({
      title: "操作失败",
      icon: "none",
    });
  }
};

// 规格选择相关方法
// 打开规格选择弹窗
const openSpecPopup = (type = "cart") => {
  buyType.value = type;
  specPopup.value.open();
};

// 处理规格选择确认
const handleSpecConfirm = ({ sku, quantity }) => {
  if (!sku || !sku.id) {
    uni.showToast({
      title: "无效的商品规格",
      icon: "none",
    });
    return;
  }

  // 更新选中的SKU
  selectedSku.value = sku;

  if (buyType.value === "cart") {
    handleAddToCart(sku.id, quantity);
  } else {
    handleBuyNow(sku.id, quantity);
  }
};

// 加入购物车
const handleAddToCart = async (skuId, num) => {
  try {
    // 检查登录状态
    if (!userStore.checkLogin()) {
      uni.navigateTo({
        url: `/pages/login/login?redirect=${encodeURIComponent(
          "/pages/goods/detail?spuId=" + goodsInfo.value.id
        )}`,
      });
      return;
    }

    // 检查是否需要选择规格
    // 多规格商品必须选择规格
    if (goodsInfo.value.openSpec === 1 && !selectedSku.value) {
      openSpecPopup("cart");
      return;
    }

    // 获取选中的 SKU 信息
    const targetSku = selectedSku.value || {
      id: goodsInfo.value.id,
      salePrice: goodsInfo.value.salePrice,
      linePrice: goodsInfo.value.linePrice
    };

    // 构建购物车商品数据
    const cartData = {
      spuId: goodsInfo.value.id,
      skuId: targetSku.id,
      title: goodsInfo.value.name,
      primaryImage: goodsInfo.value.images[0],
      salePrice: targetSku.salePrice,
      quantity: num || 1,
      selected: true,
      specs: goodsInfo.value.openSpec === 1 ? selectedSpecText.value : '单规格',
      linePrice: targetSku.linePrice,
      unit: goodsInfo.value.unit,
      code: targetSku.code
    };

    // 添加到购物车
    await cartStore.addToCart(cartData);

    uni.showToast({
      title: "添加成功",
      icon: "success",
    });

    // 关闭规格弹窗
    specPopup.value?.close();

    // 更新购物车角标
    cartStore.updateTabBarBadge();
  } catch (error) {
    console.error("添加购物车失败:", error);
    uni.showToast({
      title: error.message || "添加失败",
      icon: "none",
    });
  }
};

// 立即购买
const handleBuyNow = (skuId, num) => {
  try {
    // 检查登录状态
    if (!userStore.checkLogin()) {
      uni.navigateTo({
        url: `/pages/login/login?redirect=${encodeURIComponent(
          "/pages/goods/detail?spuId=" + goodsInfo.value.id
        )}`,
      });
      return;
    }

    // 检查是否需要选择规格
    // 直接使用 openSpec 判断是否需要选择规格
    if (goodsInfo.value.openSpec === 1 && !skuId) {
      openSpecPopup("buy");
      return;
    }

    // 构建请求参数
    const params = {
      skuId: skuId || goodsInfo.value.id,
      quantity: num || 1,
    };

    console.log("立即购买参数:", params);

    uni.navigateTo({
      url: `/pages/order/create?${Object.entries(params)
        .map(([key, value]) => `${key}=${value}`)
        .join("&")}`,
    });
  } catch (error) {
    uni.showToast({
      title: error.message || "请选择商品规格",
      icon: "none",
    });
  }
};

// 页面导航
const navTo = (url) => {
  if (url.startsWith("/pages/index") || url.startsWith("/pages/cart")) {
    uni.switchTab({ url });
  } else {
    uni.navigateTo({ url });
  }
};

// 页面加载时执行
onLoad((options) => {
  const spuId = options.spuId;
  if (spuId) {
    getGoodsDetail(spuId);
    checkCollect(spuId);
  }
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  padding-bottom: 180rpx;
  background-color: #f8f8f8;
}

.swiper {
  width: 100%;
  height: 750rpx;

  .slide-image {
    width: 100%;
    height: 100%;
  }
}

.price-section {
  padding: 32rpx;
  background-color: #fff;

  .price-row {
    display: flex;
    align-items: baseline;
    margin-bottom: 16rpx;

    .current-price {
      font-size: 48rpx;
      color: #ff4444;
      font-weight: bold;
    }

    .original-price {
      margin-left: 16rpx;
      color: #999;
      text-decoration: line-through;
    }

    .sales {
      margin-left: auto;
      color: #999;
      font-size: 28rpx;
    }
  }

  .tags-row {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .discount-tag {
      background-color: #fff1f0;
      color: #ff4444;
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
      font-size: 24rpx;
    }

    .coupon-link {
      margin-left: auto;
      color: #ff4444;
      font-size: 28rpx;
      display: flex;
      align-items: center;

      .icon-arrow {
        margin-left: 4rpx;
      }
    }
  }
}

.title-section {
  padding: 32rpx;
  display: flex;
  background-color: #fff;
  margin-top: 2rpx;

  .product-title {
    flex: 1;
    font-size: 32rpx;
    line-height: 1.4;
    margin-right: 32rpx;
  }

  .share-btn {
    color: #666;
    font-size: 28rpx;
    background: none;
    border: none;
    padding: 0;
    margin: 0;

    &::after {
      display: none;
    }
  }
}

.selection-section {
  padding: 32rpx;
  background-color: #fff;
  margin-top: 20rpx;
  cursor: pointer;

  .selection-row {
    display: flex;
    align-items: center;

    .label {
      color: #999;
      margin-right: 32rpx;
      font-size: 28rpx;
    }

    .value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }

    .icon-arrow {
      color: #999;
      font-size: 32rpx;
    }
  }

  // 单规格时移除点击效果
  &:active {
    opacity: 1;
  }

  // 多规格时添加点击效果
  &[data-openspec="1"]:active {
    opacity: 0.7;
  }
}

.rating-section {
  padding: 32rpx;
  background-color: #fff;
  margin-top: 20rpx;

  .rating-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .rating-title {
      font-size: 28rpx;
      font-weight: 500;
    }

    .rating-more {
      color: #666;
      font-size: 28rpx;
      display: flex;
      align-items: center;

      .rating-score {
        margin-right: 8rpx;
      }

      .icon-arrow {
        color: #999;
      }
    }
  }
}

.action-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 180rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);

  .action-buttons {
    display: flex;
    gap: 32rpx;

    .icon-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 24rpx;
      color: #666;
      padding: 10rpx 0;

      uni-icons {
        margin-bottom: 12rpx;
      }
    }
  }

  .main-buttons {
    flex: 1;
    display: flex;
    gap: 16rpx;
    margin-left: 32rpx;

    button {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      font-size: 28rpx;
      border-radius: 44rpx;
      margin: 0;
      padding: 0;

      &::after {
        display: none;
      }
    }

    .add-cart-btn {
      background-color: #fff1f0;
      color: #ff4444;
      border: 2rpx solid #ff4444;
    }

    .buy-btn {
      background-color: #ff4444;
      color: #fff;
      border: none;
    }
  }
}
</style>
